<script setup lang="ts">
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { useTabsStore } from '@/stores/tabs'

const route = useRoute()
const router = useRouter()
const tabsStore = useTabsStore()

// 当前激活状态由路由决定
const isTabActive = (tab) => {
    return route.path === tab.path // 精确匹配
}

// 关闭标签页
const handleTabRemove = (path: string) => {
    tabsStore.removeTab(path)
    if (tabsStore.activeTab === path) {
        router.push(tabsStore.activeTab)
    }
}
</script>

<template>
    <div class="tags-view-container">
        <el-scrollbar class="tags-wrap">
            <router-link v-for="tab in tabsStore.tabs" :key="tab.path" :to="{ path: tab.fullPath }" custom
                v-slot="{ navigate }">
                <div class="tags-item" :class="{ active: isTabActive(tab) }" @click="navigate"
                    @contextmenu.prevent="openMenu($event, tab)">
                    <span>{{ tab.title }}</span>
                    <el-icon v-if="!isTabActive(tab) && tabsStore.tabs.length > 1"
                        @click.stop="handleTabRemove(tab.path)">
                        <IEpClose />
                    </el-icon>
                </div>
            </router-link>
        </el-scrollbar>
    </div>
</template>

<style scoped>
.tags-view-container {
    height: 40px;
    line-height: 36px;
    background: #fff;
    border-bottom: 1px solid #d8dce5;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12);
}

.tags-wrap {
    height: 100%;
    padding: 2px 10px;
    white-space: nowrap;
}

.tags-item {
    display: inline-flex;
    align-items: center;
    padding: 0 8px;
    height: 26px;
    line-height: 26px;
    border: 1px solid #d8dce5;
    color: #495060;
    background: #fff;
    margin-right: 5px;
    border-radius: 2px;
    cursor: pointer;

    &:hover {
        background-color: #f0f2f5;
    }

    &.active {
        color: #fff;
        background-color: #409eff;
        border-color: #409eff;

        &::before {
            content: '';
            background: #fff;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 4px;
        }
    }

    .el-icon {
        margin-left: 4px;
        font-size: 12px;

        &:hover {
            color: #fff;
            background: #c0c4cc;
            border-radius: 50%;
        }
    }
}
</style>